leetcode 125. 驗證迴文串

1 題目描述

給定一個字符串,驗證它是否是迴文串,只考慮字母和數字字符,可以忽略字母的大小寫。

說明:本題中,我們將空字符串定義爲有效的迴文串。

示例 1:

輸入: “A man, a plan, a canal: Panama”
輸出: true

示例 2:

輸入: “race a car”
輸出: false

2 注意事項

看清題目要求,只考慮字母和數字字符

class Solution {
    public boolean isPalindrome(String s) {
        s = s.toLowerCase();
        int low = 0, high = s.length()-1;
        while (low < high) {
            String a = s.charAt(low)+"";
            while (!a.matches("[a-z|0-9]")) {
                low++;
                if (low >= high) return true;
                a = s.charAt(low)+"";
            }

            a = s.charAt(high)+"";
            while (!a.matches("[a-z|0-9]")) {
                high--;
                if (low >= high) return true;
                a = s.charAt(high)+"";
            }

            if (s.charAt(low++) != s.charAt(high--)) return false;
        }
        return true;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章